package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.store.FameStore;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.FameListEntity;
import com.zw.yzk.kabu.data.network.service.FameListService;
import com.zw.yzk.kabu.data.network.task.FameListTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/12.
 */

public class FameListRepository extends CommonRepository {

    @Inject
    FameStore fameStore;
    private int totalCount;
    private boolean refresh;

    @Inject
    public FameListRepository() {
        totalCount = FameListTask.DEFAULT_FAME_COUNT_PER_PAGE;
    }

    @Override
    protected Observable commonObserve(Task task) {
        if (((FameListTask) task).getLocal) {
            return Observable.concat(Observable.just(fameStore.getFrameList()), super.commonObserve(task));
        } else {
            return super.commonObserve(task);
        }

    }

    @Override
    protected Observable connectServer(Task task) {
        FameListService service = ServiceGenerator.createService(FameListService.class);
        FameListTask fameListTask = (FameListTask) task;

        refresh = fameListTask.start == 0;
        if (fameListTask.start >= totalCount) {
            FameListEntity entity = new FameListEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.totalCount = totalCount;

            return Observable.just(entity);
        } else {
            //加载网络数据
            return service.getFameList(fameListTask.start, fameListTask.size);
        }
    }

    @Override
    protected Func1<FameListEntity, Observable> getServerData() {
        return new Func1<FameListEntity, Observable>() {
            @Override
            public Observable call(FameListEntity fameListEntity) {
                totalCount = fameListEntity.result.totalCount;
                saveFameList(refresh, fameListEntity);

                return Observable.just(fameListEntity);
            }
        };
    }

    /**
     * 保存名人堂列表
     */
    private void saveFameList(boolean refresh, FameListEntity entity) {
        if (refresh) {
            fameStore.refreshFameList(entity);
        } else {
            fameStore.addFameList(entity);
        }
    }
}
